import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import dotenv from 'dotenv';
import rateLimit from 'express-rate-limit';
import path from 'path';
import { requestLogger, errorLogger } from './middleware/logger';
import logger from './utils/logger';
import { setupSwagger } from './config/swagger';
import { testConnection } from './utils/database';
import systemRoutes from './routes/system';
import userRoutes from './routes/users';
import authRoutes from './routes/auth';
import addressRoutes from './routes/addresses';
import bannerRoutes from './routes/banners';
import categoryRoutes from './routes/categories';
import brandRoutes from './routes/brands';
import productRoutes from './routes/products';
import uploadRoutes from './routes/upload';
import publicRoutes from './routes/public';
import orderRoutes from './routes/orders';
import cartRoutes from './routes/cart';
import { notFound, errorHandler } from './middleware/errorHandler';

dotenv.config();

const app = express();
const PORT = process.env.PORT || 3000;

// 安全中间件
app.use(helmet({
  crossOriginResourcePolicy: { policy: "cross-origin" }
}));

// CORS配置
app.use(cors({
  origin: [
    'http://localhost:5173', // Vue Admin
    'http://localhost:5174', // User Frontend
    process.env.CORS_ORIGIN || 'http://localhost:5173'
  ],
  credentials: true
}));

// 请求日志中间件
app.use(requestLogger);

// 限流中间件
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100 // 限制每个IP每15分钟最多100个请求
});
app.use(limiter);

// 解析JSON
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// 静态文件服务 - 提供上传文件访问
app.use('/uploads', (req, res, next) => {
  // 为静态文件添加CORS头
  const allowedOrigins = [
    'http://localhost:5173',
    'http://localhost:5174',
    process.env.CORS_ORIGIN || 'http://localhost:5173'
  ];
  const origin = req.headers.origin;
  if (origin && allowedOrigins.includes(origin)) {
    res.header('Access-Control-Allow-Origin', origin);
  }
  res.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Cross-Origin-Resource-Policy', 'cross-origin');
  
  // Handle preflight requests
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
    return;
  }
  
  next();
}, express.static(path.join(__dirname, '../uploads')));

// 设置Swagger文档
setupSwagger(app);

// 系统路由
app.use('/', systemRoutes);

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/addresses', addressRoutes);
app.use('/api/banners', bannerRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/brands', brandRoutes);
app.use('/api/products', productRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/cart', cartRoutes);

// 公开API路由
app.use('/api/public', publicRoutes);

// 错误日志中间件（必须在错误处理之前）
app.use(errorLogger);

// 404处理
app.use(notFound);

// 全局错误处理
app.use(errorHandler);

/**
 * 启动服务器
 */
const startServer = async () => {
  try {
    // 测试数据库连接
    await testConnection();
    
    // 数据库模型同步已移除 - 使用手动创建的数据库表结构
    
    app.listen(PORT, () => {
      console.log(`小米有品API服务启动成功！`);
      console.log(`服务地址: http://localhost:${PORT}`);
      console.log(`API文档: http://localhost:${PORT}/api-docs`);
      console.log(`健康检查: http://localhost:${PORT}/health`);
      console.log(`运行环境: ${process.env.NODE_ENV || 'development'}`);
    });
  } catch (error) {
    logger.error('服务器启动失败', error);
    process.exit(1);
  }
};

startServer();

export default app;